var co = require('co');
var OSS = require('ali-oss');
var fs = require('fs');
var schedule = require("node-schedule");

var client = new OSS({
  region: 'oss-cn-beijing',
  endpoint: 'http://oss-cn-beijing.aliyuncs.com',
  accessKeyId: 'LTAImWVvyGYbGC6p',
  accessKeySecret: 'amPrViWwaatHlB7kunEoMYN8expUZC',
  bucket: 'yd-img'
});

//co(function* () {
//  var result = client.listBuckets();
//  console.log(result);
//}).catch(function (err) {
//  console.log(err);
//});

//co(function* () {
//  // put from Stream
//  var result = yield client.put('img/default_image.gif', fs.createReadStream('assets/images/default_image.gif'));
//  console.log(result);
//}).catch(function (err) {
//  console.log(err);
//});

var service = module.exports = {
  up2ossAuto: function () {
    var j = schedule.scheduleJob('*/5 * * * *', function () {

      OssService.up2oss();
    });
  },

  upImg2CDN: function (id, filePath, callback) {
    co(function* () {
      var result = yield client.put('img/' + id, fs.createReadStream(filePath));
      // console.log(result);
      var cdnPath = CdnService.CDN_HOST + '/img/' + id;
      callback(null, cdnPath);

    }).catch(function (err) {
      callback && callback(err); // tell async that the iterator has completed
      sails.log(err);
    });
  },

  upFile2Oss: function(id, filePath, callback) {//图片应该使用cdn path
    co(function* () {
      // put from Stream
      var cdnKey = id + filePath.substring(filePath.lastIndexOf('.'));
      var result = yield client.put('img/' + cdnKey, fs.createReadStream(filePath));
      // console.log("result:");
      // console.log(result);
      FileUtil.findOne({
        id: id
      }).exec(function (err, fu) {
        if (err) {
          return callback && callback(err);
        }
        fu.cdnPath = '/img/' + fu.id;
        // console.log(fu)
        fu.save(function (err, saved) {
          //console.log(err);
          //console.log(saved);
          // console.log('upload to oss success! >' + saved.id + '->' + saved.ossPath + '->' + saved.cdnPath);
          callback && callback(null, cdnKey); // tell async that the iterator has completed
        });
      });
    }).catch(function (err) {
      callback && callback(err); // tell async that the iterator has completed
      console.log(err);
    });
  },

  // up dir files to oss
  up2oss: function () {
    FileUtil.find({
      where: {
        'cdnPath': null
        //'cdnPath': {
        //  '!': null
        //}
      },
      limit: 5
    }).exec(function (err, list) {
      if (err) {
        return;
      }
      console.log('update file to oss:' + list.length);

      async.forEach(list, function (item, callback) {
        co(function* () {
          // put from Stream
          var result = yield client.put('img/' + item.id, fs.createReadStream(item.fd));
          console.log("result:");
          console.log(result);
          console.log(item);
          FileUtil.findOne({
            id: item.id
          }).exec(function (err, fu) {
            if (err) {
              return callback();
            }
            //console.log('err:');
            //console.log(err);
            //fu.ossPath = '/img/' + fu.id;
            fu.cdnPath = '/img/' + fu.id;
            fu.save(function (err, saved) {
              //console.log(err);
              //console.log(saved);
              //console.log('upload to oss success! >' + saved.id + '->' + saved.ossPath + '->' + saved.cdnPath);
              callback(); // tell async that the iterator has completed
            });
          });
        }).catch(function (err) {
          callback(); // tell async that the iterator has completed
          console.log(err);
        });

      }, function (err) {
        console.log('update file to oss:iterating done');
        //return cb(err);
      });


    });

  }
};

